package com.example.ivideo_2211a.fabu

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.common.mvi.MviIntent
import com.example.common.mvi.MviViewState
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import org.json.JSONArray
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

sealed class PublishVideoIntent : MviIntent {
    object FetchVideoList : PublishVideoIntent()
}

sealed class PublishVideoViewState : MviViewState {
    object Idle : PublishVideoViewState()
    object Loading : PublishVideoViewState()
    data class VideoList(val list: List<VideoFaEntityItem>) : PublishVideoViewState()
    data class Error(val error: String) : PublishVideoViewState()
}

class PublishVideoViewModel : BaseViewModel<PublishVideoIntent, PublishVideoViewState, Nothing>() {
    override fun initialState(): PublishVideoViewState = PublishVideoViewState.Idle

    override suspend fun handleIntent(intent: PublishVideoIntent) {
        when (intent) {
            is PublishVideoIntent.FetchVideoList -> fetchVideoList()
        }
    }

    private fun fetchVideoList() {
        updateState(PublishVideoViewState.Loading)
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://10.161.9.80:7015/api/videos/findAll?page=1&size=10")
                    .get()
                    .build()
                val response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    val body = response.body?.string()
                    val json = JSONObject(body)
                    val dataArr = json.optJSONArray("data") ?: JSONArray()
                    val list = mutableListOf<VideoFaEntityItem>()
                    for (i in 0 until dataArr.length()) {
                        val obj = dataArr.getJSONObject(i)
                        list.add(
                            VideoFaEntityItem(
                                approved = obj.optBoolean("approved"),
                                caption = obj.optString("caption"),
                                category = obj.optString("category"),
                                commentCount = obj.optInt("commentCount"),
                                likeCount = obj.optInt("likeCount"),
                                publishTime = obj.optString("publishTime"),
                                publisherAvatar = obj.optString("publisherAvatar"),
                                publisherId = obj.optString("publisherId"),
                                tags = obj.optString("tags"),
                                thumbnailUrl = obj.optString("thumbnailUrl"),
                                title = obj.optString("title"),
                                videoId = obj.optInt("videoId"),
                                videoUrl = obj.optString("videoUrl"),
                                viewCount = obj.optInt("viewCount")
                            )
                        )
                    }
                    withContext(Dispatchers.Main) {
                        updateState(PublishVideoViewState.VideoList(list))
                    }
                } else {
                    val errBody = response.body?.string()
                    withContext(Dispatchers.Main) {
                        updateState(PublishVideoViewState.Error("加载失败：${response.code} ${errBody}"))
                    }
                }
            } catch (e: Exception) {
                val stack = e.stackTraceToString()
                withContext(Dispatchers.Main) {
                    updateState(PublishVideoViewState.Error("加载失败：${e.javaClass.simpleName}: ${e.message}\n$stack"))
                }
            }
        }
    }
}
